package com.trs.controll;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.trs.util.AppRuntimeException;
import com.trs.util.Results;

import lombok.extern.slf4j.Slf4j;

@RestControllerAdvice
@Slf4j
@SuppressWarnings("rawtypes")
public class ExceptionController {
	/**
	 * 自定义全局异常捕捉处理
	 *
	 * @param ex
	 * @return
	 */

	@ExceptionHandler(value = AppRuntimeException.class)
	public Results errorHandler(AppRuntimeException e) {
		if (e.getCode() != null && e.getCode() == 1) {
			log.error("运行异常 : ", e);
		} else {
			log.info("运行异常 : ", e);
		}

		return Results.error("运行异常 : " + e.getMessage());
	}

	/**
	 * 全局异常捕捉处理
	 *
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(value = Exception.class)
	public Results errorHandler(Exception ex) {
		log.error(ex.getMessage(), ex);
		Results restfulResults;
		if (ex.getClass().isAssignableFrom(AppRuntimeException.class)) {
			restfulResults = Results.error("全局异常 : " + ex.getMessage());
		} else if (ex.getClass().isAssignableFrom(NullPointerException.class)) {
			restfulResults = Results.error("出现空指针异常 : " + ex.getMessage());
		} else {
			restfulResults = Results.error("全局异常 : " + ex.getMessage());
		}
		return restfulResults;
	}

}
